package edu.cmu.javadb.plan.condition;

import java.lang.reflect.*;
import java.util.*;

import edu.cmu.javadb.Attribute;
import edu.cmu.javadb.RecordInfo;
import edu.cmu.javadb.exceptions.NoAttributeException;

public class Greater extends Condition {

	private Path left;
	private Object right;

	public Greater(Path field, Object val) {
		this.left = field;
		this.right = val;
	}

	// @Override
	// public List<String> getAllFieldNames() {
	// List<String> res = new ArrayList<String>();
	// if (left instanceof Path) {
	// res.add(left.toString());
	// }
	// return res;
	// }

	@Override
	public List<Attribute> getAllFields(RecordInfo recInfo) {
		List<Attribute> res = new ArrayList<Attribute>();

		try {
			if (!left.isRoot())
				res.add(recInfo.getAttribute(left.getPath()));
		} catch (NoAttributeException e) {
			e.printStackTrace();
		}
		return res;
	}

	public boolean hasValue() {
		return !(right instanceof Path);
	}

	// @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public boolean satisfy(Object o) {
		try {
			Object v1 = getValue(o, left);
			Object v2 = getValue(o, right);

			if (v1.getClass() != v2.getClass()) {
				System.err.println("Type not match?");
				// TODO exception handle
			}

			if (v1 instanceof Comparable) {
				Comparable c1 = (Comparable) v1;
				Comparable c2 = (Comparable) v2;

				return c1.compareTo(c2) > 0;
			} else {
				//TODO check if this is right
				return v1.toString().compareTo(v2.toString()) > 0;
			}

		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return false;
	}

	public Object getRight() {
		return right;
	}

	public Object getLeft() {
		return left;
	}

	@Override
	public boolean containRootPath() {
		return left.isRoot();
	}

	@Override
	public boolean containNonValBinary() {
		return !hasValue();
	}

}
